import axios from 'axios';
import store from '../store';

const BASE_URL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_PATH : window.location.origin;

export const loadingFetch = option => {
  const service = axios.create({
    baseURL: BASE_URL, // api的base_url
    timeout: 30000 // request timeout
  });
  // service interceptor
  service.interceptors.request.use(
    config => {
      store.dispatch('showLoading');
      return config;
    }
  );
  // respone interceptor
  service.interceptors.response.use(
    response => {
      store.dispatch('hideLoading');
      return response.data;
    },
    error => {
      store.dispatch('hideLoading');
      return Promise.reject(error);
    }
  );
  return service(option);
};

export const fetch = option => {
  const service = axios.create({
    baseURL: BASE_URL, // api的base_url
    // headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    timeout: 30000 // request timeout
  });
  service.interceptors.response.use(
    response => response.data,
    error => Promise.reject(error)
  );
  return service(option);
};
